<?php

namespace app\common\model;

use app\common\basic\BaseModel;
use app\common\model\SystemUser;

/**
 * 客户跟进记录模型
 */
class CrmFollowUps extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';
    protected $table = 'vk_crm_follow_ups';


    /**
     * 关联客户
     * @return \think\model\relation\BelongsTo
     */
    public function customer()
    {
        // 关联的客户信息, 仅需要返回部分metas中的字段
        return $this->belongsTo(CrmCustomers::class, 'customer_id', 'id')->field('id, province_id, city_id, area_id, stage, province_id province, city_id city, area_id area')->with(['metas' => function($query) {
            return $query->whereIn('meta_key', ['contact_person', 'contact_name', 'brands', 'address', 'phone'])->field('customer_id, meta_key, meta_value');
        }]);
    }
    

    /**
     * 跟进方式搜索器
     */
    public function searchTypeAttr($query, $value)
    {
        $query->where('type', $value);
    }

    /**
     * 内容搜索器
     */
    public function searchContentAttr($query, $value)
    {
        $query->where('content', 'like', '%' . $value . '%');
    }

    /**
     * 操作人ID搜索器
     */
    public function searchUserIdAttr($query, $value)
    {
        $query->where('user_id', $value);
    }

    /**
     * 创建时间搜索器
     */
    public function searchCreateTimeAttr($query, $value)
    {
        $query->whereTime('create_time', 'between', $value);
    }

    // 关联跟进人
    public function user()
    {
        return $this->belongsTo(SystemUser::class, 'user_id', 'id')->field('id,username,nickname,avatar');
    }

    // 关联陪同人
    public function partner()
    {
        return $this->belongsTo(SystemUser::class, 'partner_id', 'id')->field('id,username,nickname,avatar');
    }

    public function getImagesAttr($value, $data)
    {
        return json_decode($value, true);
    }

    public function getRegionAttr($value, $data)
    {
        // 根据省市区id获取名称
        $regionData = SystemRegion::whereIn('id', [$data['province_id'], $data['city_id'], $data['area_id']])->column('name', 'id');
        $regionNames = [];
        if (!empty($regionData[$data['province_id']])) {
            $regionNames[] = $regionData[$data['province_id']];
        }
        if (!empty($regionData[$data['city_id']])) {
            $regionNames[] = $regionData[$data['city_id']];
        }
        if (!empty($regionData[$data['area_id']])) {
            $regionNames[] = $regionData[$data['area_id']];
        }
        return implode('-', $regionNames);
    }
    
    public function getProvinceAttr($value, $data)
    {
        return SystemRegion::where('id', $data['province_id'])->value('name');
    }   
    
    public function getCityAttr($value, $data)
    {
        return SystemRegion::where('id', $data['city_id'])->value('name');
    }
    
    public function getAreaAttr($value, $data)
    {
        return SystemRegion::where('id', $data['area_id'])->value('name');
    }
}